package com.sinog.biz.service.business.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinog.biz.config.ProvinceCodes3Config;
import com.sinog.biz.config.ProvinceCodesConfig;
import com.sinog.biz.config.ThreadPoolConfig;
import com.sinog.biz.interceptor.CodesHelper;
import com.sinog.biz.mapper.havexml.AreaCodeFullMapper;
import com.sinog.biz.mapper.havexml.ChangeTableMapper;
import com.sinog.biz.mapper.havexml.DepartmentMapper;
import com.sinog.biz.mapper.havexml.HnInterfaceOppositeMapper;
import com.sinog.biz.mapper.havexml.PrisonerFxMapper;
import com.sinog.biz.mapper.havexml.PrisonerMainMapper;
import com.sinog.biz.mapper.havexml.PrisonerSrMapper;
import com.sinog.biz.mapper.havexml.PrisonerTsMapper;
import com.sinog.biz.mapper.havexml.PrisonerZnMapper;
import com.sinog.biz.mapper.havexml.SystemCodeMapper;
import com.sinog.biz.mapper.havexml.VerificationMapper;
import com.sinog.biz.mapper.havexml.XjReceiptMapper;
import com.sinog.biz.mapper.havexml.other.UserLoginDetailsMapper;
import com.sinog.biz.service.api.XmlMinitoringService;
import com.sinog.biz.service.business.VerificationService;
import com.sinog.biz.service.xml.InterfaceDockingService;
import com.sinog.biz.util.BusinessUtils;
import com.sinog.biz.util.CodeUrlUtils;
import com.sinog.biz.util.ConditionUtils;
import com.sinog.biz.util.IdGen;
import com.sinog.biz.util.smlib.Sm4;
import com.sinog.core.domain.Department;
import com.sinog.core.domain.PrisonerHc;
import com.sinog.core.domain.PrisonerMain;
import com.sinog.core.domain.PrisonerTs;
import com.sinog.core.domain.User;
import com.sinog.core.domain.XjReceipt;
import com.sinog.core.domain.xml.HnInterfaceOpposite;
import com.sinog.core.model.PrisonerTsVo;
import com.sinog.core.model.UserDTO;
import com.sinog.core.model.xml.HnMessageVo;
import com.sinog.core.util.AssemblyConversionUtils;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.util.StrUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Dictionary;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @desc 核查列表
 * @author -
 * @date 2020-01-19-14:02
 */
@Slf4j
@Service
public class VerificationServiceImpl extends ServiceImpl<VerificationMapper,PrisonerHc> implements VerificationService {

    @Autowired
    private XjReceiptMapper xjReceiptMapper;
    @Autowired
    private PrisonerFxMapper prisonerFxMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SystemCodeMapper systemCodeMapper;
    @Resource
    private VerificationMapper verificationMapper;
    @Autowired
    @Qualifier("middleJdbcTemplate")
    private JdbcTemplate middleJdbcTemplate;
    @Autowired
    private PrisonerMainMapper prisonerMainMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private PrisonerTsMapper prisonerTsMapper;
    @Autowired
    private XmlMinitoringService xmlMinitoringService;
    @Autowired
    private HnInterfaceOppositeMapper hnInterfaceOppositeMapper;
    @Autowired
    private UserLoginDetailsMapper userLoginDetailsMapper;
    @Autowired
    private ThreadPoolConfig threadPoolConfig;
    @Autowired
    private InterfaceDockingService interfaceDockingService;
    @Resource
    private AreaCodeFullMapper areaCodeFullMapper;
    @Resource
    private ProvinceCodes3Config provinceCodes3Config;
    @Resource
    private PrisonerSrMapper prisonerSrMapper;
    @Resource
    private PrisonerZnMapper prisonerZnMapper;
    @Resource
    private ChangeTableMapper changeTableMapper;

    /**
     * 初始化字典表
     */
    private static final Dictionary DICTIONARY = Dictionary.getSingleton();

    /**
     * 预安置管理 - 预安置人员核查 - 列表
     * @param pageIndex 起始页 默认:0
     * @param pageSize 止页数 默认:50
     * @param sortField 排序字段
     * @param sortOrder 排序方式
     * @param departId 当前登录用户机构编码
     * @param level 当前登录用户level
     * @param state 1:待核查 2:核查中 3:核查成功人员 4:核查失败人员 5:待办工作 6:已办工作
     * @param nameKey 姓名
     * @param sexKey 性别 1:男、2:女
     * @param hjKey 户籍类型 01:户籍完整人员、02:查不清户籍人员
     * @param inputSource 录入来源 01:司法所补录的解矫人员,05:司法所补录的监狱人员,3.看守所录入的服刑人员,4:接口进入的看守所人员,5:监狱录入的服刑人员,6:接口进入的监狱服刑人员,7:社矫录入的服刑人员,8:接口进入的社矫人员,9:监狱通过excel导入,10:社矫通过excel导入,11:看守所通过excel导入,30:湖南看守所个性化对接
     * @param account account
     * @param hcType 核查成功类别 1:一次核查成功、2:二次核查成功、3:三次核查成功、4:查不清户籍核查成功
     * @param zdbjKey 重点帮教对象 1:是、2:否
     * @param shenKey 身份证
     * @param zmKey 罪名
     * @param fxKey 服刑单位
     * @param qitaKeyStr 其他条件
     * @param nativepro 省
     * @param nativecity 市
     * @param nativecou 区
     * @param nativevill 街道
     * @param rjStartDate 原判刑期起日
     * @param rjEndDate 释放日期
     * @return String
     */
    @Override
    public String getVerificationList(Integer pageIndex,Integer pageSize,String sortField,String sortOrder,String departId,String level,String state,String sexKey,String nameKey,String hjKey,String inputSource,String account,String hcType,String zdbjKey,String shenKey,String zmKey,String fxKey,String qitaKeyStr,String nativepro,String nativecity,String nativecou,String nativevill,String rjStartDate,String rjEndDate) {
        List<String> qitaKey = null;
        if(StringUtils.isNotBlank(qitaKeyStr)) {
            String[] split = qitaKeyStr.split(",");
            qitaKey = Arrays.asList(split);
        }
        if(StringUtils.equals(sortField,Constants.NumberStr.NUM_STR_FU_ONE)) {
            sortField = null;
        }
        if(StringUtils.equals(sortOrder,Constants.NumberStr.NUM_STR_FU_ONE)) {
            sortOrder = null;
        }
        if(StringUtils.equals(sexKey,Constants.NumberStr.NUM_STR_FU_ONE)) {
            sexKey = null;
        }
        if(StringUtils.equals(nameKey,Constants.NumberStr.NUM_STR_FU_ONE)) {
            nameKey = null;
        }
        if(StringUtils.equals(hjKey,Constants.NumberStr.NUM_STR_FU_ONE)) {
            hjKey = null;
        }
        if(StringUtils.equals(inputSource,Constants.NumberStr.NUM_STR_FU_ONE)) {
            inputSource = null;
        }
        if(StringUtils.isNotBlank(shenKey)) {
            shenKey = Sm4.encryptEcb(shenKey);
        }
        String localCode = CodeUrlUtils.getLocalCode();
        // 根据level组装转换参数
        Map<String,Object> resultMap = AssemblyConversionUtils.transferAssembly(level);
        Page<Map<String,String>> page = new Page<>(pageIndex + 1,pageSize);
        page.setSearchCount(false);
        long count = prisonerMainMapper.getVerificationListCount(departId,level,state,sexKey,nameKey,hjKey,inputSource,zdbjKey,shenKey,zmKey,fxKey,qitaKey,nativepro,nativecity,nativecou,nativevill,rjStartDate,rjEndDate,hcType,resultMap,null,null);
        List<Map<String,String>> verificationList = prisonerMainMapper.getVerificationList(page,sortField,sortOrder,departId,level,state,sexKey,nameKey,hjKey,inputSource,zdbjKey,shenKey,zmKey,fxKey,qitaKey,nativepro,nativecity,nativecou,nativevill,rjStartDate,rjEndDate,hcType,resultMap,localCode);
        //把监狱与和对应的省份匹配
        Map<Object,Object> mapProvince = stringRedisTemplate.opsForHash().entries("province");
        for(Map<String,String> item : verificationList) {
            if(StringUtils.isEmpty(item.get("pdanweiName"))) {
                item.put("pdanweiName","");
            } else if(mapProvince.get(item.get("prinum").substring(0,2) + "0000")!=null) {
                item.put("pdanweiName",mapProvince.get(item.get("prinum").substring(0,2) + "0000") + "-" + item.get("pdanweiName"));
            }
        }
        Map<String,String> searchMap = new HashMap<>(16);
        searchMap.put("pageIndex",pageIndex.toString());
        searchMap.put("pageSize",pageSize.toString());
        searchMap.put("sortField",sortField);
        searchMap.put("sortOrder",sortOrder);
        searchMap.put("departid",departId);
        searchMap.put("level",level);
        searchMap.put("state",state);
        searchMap.put("sexKey",sexKey);
        searchMap.put("nameKey",nameKey);
        searchMap.put("hjKey",hjKey);
        searchMap.put("inputSource",inputSource);
        searchMap.put("account",account);
        searchMap.put("zdbjKey",zdbjKey);
        searchMap.put("shenKey",shenKey);
        searchMap.put("zmKey",zmKey);
        searchMap.put("fxKey",fxKey);
        searchMap.put("qitaKey",qitaKeyStr);
        searchMap.put("nativepro",nativepro);
        searchMap.put("nativecity",nativecity);
        searchMap.put("nativecou",nativecou);
        searchMap.put("nativevill",nativevill);
        searchMap.put("rjStartDate",rjStartDate);
        searchMap.put("rjEndDate",rjEndDate);
        searchMap.put("total",String.valueOf(count));
        CompletableFuture.runAsync(()->{
            ConditionUtils.fzSearchKey(searchMap,redisTemplate);
        });
        return JsonUtil.toText(count,verificationList);
    }

    /**
     * todo:取消事务的原因是跨省问题，需要处理
     * 修改核查状态
     * @param priNum 罪犯编号
     * @param state 0:未发起核查 1:核查中
     * @param data data
     * @param userDTO 当前用户账号
     * @return Result
     */
    @Override
    public Result updateHcState(String priNum,String state,String data,UserDTO userDTO) throws ParseException {
        /*审核人姓名手机号改为手动录入   审核人账号仍是查询数据  存在不一致（可能）*/
        Map<String,String> paramMap = new HashMap<>(16);
        PrisonerHc prisonerHc = new PrisonerHc();
        PrisonerTs prisonerTs = new PrisonerTs();
        Date date = new Date();
        prisonerTs.setId(IdGen.strid());
        prisonerTs.setUpdateTime(date);
        prisonerTs.setUpdateUser(userDTO.getAccount());
        prisonerTs.setCreateTime(date);
        prisonerTs.setCreateUser(userDTO.getAccount());
        PrisonerMain prisonerMain = new PrisonerMain();
        prisonerMain.setUpdateUser(userDTO.getAccount());
        prisonerMain.setUpdateTime(date);
        prisonerMain.setPriNum(priNum);
        PrisonerMain mainParam = prisonerMainMapper.selectPrisonerMain(priNum);
        prisonerMain.setAge(mainParam.getAge() != null ? mainParam.getAge() : null);
        prisonerHc.setUpdateUser(userDTO.getAccount());
        prisonerHc.setUpdateTime(date);
        prisonerHc.setPriNum(priNum);
        paramMap.put("priNum",priNum);
        paramMap.put("signFlag",Constants.NumberStr.NUM_STR_ZERO);
        String conmectuserTelphone = null;
        //如果是核查失败，data数据为默认值-1,此时需要判断data,不然报错
        if(!Constants.NumberStr.NUM_STR_FU_ONE.equals(data) && StringUtils.isNotBlank((String)JsonUtil.toMap(data)
                                                                                                      .get("conmectuserTelphone"))) {
            conmectuserTelphone = JsonUtil.toMap(data).get("conmectuserTelphone").toString();
        }
        int b = 0;
        boolean b1 = false;
        //监所人员发起核查
        if(StringUtils.equals(state,Constants.NumberStr.NUM_STR_ONE)) {
            Map<String,Object> dataMap = JsonUtil.toMap(data);
            prisonerHc = prisonerMainMapper.prisonerHcByPriNum(priNum);
            if(null == prisonerHc.getId()) {
                prisonerHc.setId(IdGen.strid());
            }
            prisonerHc.setUpdateTime(date);
            prisonerHc.setUpdateUser(userDTO.getAccount());
            prisonerHc.setCreateTime(date);
            prisonerHc.setCreateUser(userDTO.getAccount());
            String startCheckTimeStr = dataMap.get("startCheckTime").toString().replace("T"," ");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date startCheckTime = simpleDateFormat.parse(startCheckTimeStr);
            prisonerHc.setStartCheckPerson(dataMap.get("startCheckPerson").toString());
            prisonerHc.setStartCheckTime(startCheckTime);
            prisonerHc.setStartCheckPhone(dataMap.get("startCheckPhone").toString());
            prisonerHc.setStartCheckTel(dataMap.get("startCheckTel").toString());
            prisonerHc.setPushState(Constants.NumberStr.NUM_STR_ZERO);
            prisonerHc.setFailurenum(Constants.NumberStr.NUM_STR_ZERO);
            prisonerHc.setSpecialFlag(Constants.NumberStr.NUM_STR_ZERO);
            prisonerHc.setSignFlag(Constants.NumberStr.NUM_STR_ZERO);
            // 将查询出来的核查记录赋值
            prisonerHc.setXjrctId(prisonerTs.getId());
            b1 = prisonerHc.insertOrUpdate();
            prisonerMain.setState(Constants.NumberStr.NUM_STR_TWO);
            // 获得接收方的code 和 name
            String sfsId = mainParam.getNativevill();
            String sfsName = mainParam.getNativevillName();
            // 往回执中间表中插入一条数据
            XjReceipt xjReceipt = new XjReceipt();
            xjReceipt.setXjid(prisonerHc.getXjrctId());
            xjReceipt.setPriNum(priNum);
            xjReceipt.setSendCode(userDTO.getDepartid());
            xjReceipt.setSendName(userDTO.getDepartName());
            xjReceipt.setReceiveCode(null == sfsId ? "" : sfsId);
            xjReceipt.setReceiveName(null == sfsName ? "" : sfsName);
            xjReceipt.setSessionFlag(Constants.NumberStr.NUM_STR_ZERO);
            xjReceipt.setFlag(Constants.NumberStr.NUM_STR_ONE);
            xjReceipt.setCreateUser(userDTO.getAccount());
            xjReceipt.setUpdateUser(userDTO.getAccount());
            xjReceipt.setCreateTime(date);
            xjReceipt.setUpdateTime(date);
            xjReceiptMapper.saveXjReceive(xjReceipt);
            // 填充prisonerTs信息
            prisonerTs.setPriNum(prisonerHc.getId());
            prisonerTs.setPhoneNumber(dataMap.get("startCheckPhone").toString());
            prisonerTs.setFixedlineNumber(dataMap.get("startCheckTel").toString());
            prisonerTs.setType(Constants.NumberStr.NUM_STR_NINE);
            prisonerTs.setAdduserId(userDTO.getDepartid());
            // 监狱发起核查将push_state置为0
            // 司法所核查成功
        } else if(StringUtils.equals(state,Constants.NumberStr.NUM_STR_THREE)) {
            PrisonerHc prisonerHc1 = JsonUtil.toBean(data,PrisonerHc.class);
            prisonerMain.setState(Constants.NumberStr.NUM_STR_THREE);
            prisonerMain.setStateXj(Constants.NumberStr.NUM_STR_FOUR);
            prisonerHc.setConnecttime(date);
            prisonerHc.setConmectuserid(userDTO.getAccount());
            prisonerHc.setConmectuserName(prisonerHc1.getConmectuserName());
            String conmectuserPhone = prisonerHc1.getConmectuserPhone();
            if(!StringUtils.isEmpty(conmectuserTelphone)) {
                conmectuserPhone = conmectuserPhone + "|" + conmectuserTelphone;
            }
            prisonerHc.setConmectuserPhone(conmectuserPhone);
            prisonerHc.setPriReason(prisonerHc1.getPriReason());
            verificationMapper.updatePrisonerHcByParam(prisonerHc,paramMap);
            //判断是否湖南个性化对接数据
            Result result = interfaceDockingService.getHnInterfaceOppositeByPriNum(priNum);
            if(Constants.Number.NUM_ONE.equals(result.getCode())) {
                hcResult(mainParam,prisonerHc,true);
            }
            // 填充prisonerTs信息
            prisonerTs.setPriNum(prisonerHc1.getId());
            prisonerTs.setPhoneNumber(prisonerHc1.getConmectuserPhone());
            prisonerTs.setFixedlineNumber(conmectuserTelphone);
            prisonerTs.setType(Constants.NumberStr.NUM_STR_TEN_FOUR);
            prisonerTs.setPriReason(prisonerHc1.getPriReason());
            prisonerTs.setAdduserId(userDTO.getDepartid());
            //司法所核查失败
        } else if(StringUtils.equals(state,Constants.NumberStr.NUM_STR_FOUR)) {
            PrisonerHc prisonerHc1 = JsonUtil.toBean(data,PrisonerHc.class);
            prisonerMain.setState(Constants.NumberStr.NUM_STR_FOUR);
            // 司法所核查失败,默认上报数据到司法局
            prisonerHc.setUpdateTime(date);
            prisonerHc.setUpdateUser(userDTO.getAccount());
            prisonerHc.setPushState(Constants.NumberStr.NUM_STR_ONE);
            prisonerHc.setPriReason(prisonerHc1.getPriReason());
            prisonerHc.setConnecttime(date);
            prisonerHc.setConmectuserid(userDTO.getAccount());
            prisonerHc.setConmectuserName(prisonerHc1.getConmectuserName());
            String conmectuserPhone = prisonerHc1.getConmectuserPhone();
            if(!StringUtils.isEmpty(conmectuserTelphone)) {
                conmectuserPhone = conmectuserPhone + "|" + conmectuserTelphone;
            }
            prisonerHc.setConmectuserPhone(conmectuserPhone);
            verificationMapper.updatePrisonerHcByParam(prisonerHc,paramMap);
            //判断是否湖南个性化对接数据
            Result result = interfaceDockingService.getHnInterfaceOppositeByPriNum(priNum);
            if(Constants.Number.NUM_ONE.equals(result.getCode())) {
                hcResult(mainParam,prisonerHc,false);
            }
            // 填充prisonerTs信息
            prisonerTs.setPriNum(prisonerHc1.getId());
            prisonerTs.setPhoneNumber(prisonerHc1.getConmectuserPhone());
            prisonerTs.setFixedlineNumber(conmectuserTelphone);
            prisonerTs.setType(Constants.NumberStr.NUM_STR_TEN_THREE);
            prisonerTs.setAdduserId(userDTO.getDepartid());
            prisonerTs.setPriReason(prisonerHc1.getPriReason());
            //监所人员撤回核查
        } else if(StringUtils.equals(state,Constants.NumberStr.NUM_STR_ZERO)) {
            // 山西个性化需求,监狱撤回核查时，删除高亮表中记录
            String localCode = CodeUrlUtils.getLocalCode();
            if(Constants.XzqhCode.SHAN1XI.equals(localCode)) {
                List<String> srList = prisonerSrMapper.searchPrisonerSrByPriNum(priNum);
                List<String> znList = prisonerZnMapper.searchPrisonerZnByPriNum(priNum);
                srList.add(priNum);
                srList.addAll(znList);
                changeTableMapper.deleteSrZnByPriNum(srList);
            }
            PrisonerHc prisonerHc1 = verificationMapper.selectOne(new QueryWrapper<PrisonerHc>().lambda()
                                                                                                .eq(PrisonerHc::getPriNum,priNum)
                                                                                                .eq(PrisonerHc::getSignFlag,Constants.NumberStr.NUM_STR_ZERO));
            PrisonerMain prisonerMain1 = prisonerMainMapper.selectOne(new QueryWrapper<PrisonerMain>().lambda()
                    .eq(PrisonerMain::getPriNum, priNum));
            prisonerHc1.setUpdateTime(date);
            prisonerHc1.setUpdateUser(userDTO.getAccount());
            // 监狱再次发起核查撤回
            if(StringUtils.equals(prisonerMain1.getState(),Constants.NumberStr.NUM_STR_TWO)
                    && StrUtil.containsEquals(prisonerHc1.getFailurenum(),Constants.NumberStr.NUM_STR_ONE,Constants.NumberStr.NUM_STR_TWO)) {
                prisonerHc1.setPushState(Constants.NumberStr.NUM_STR_FOUR);
                prisonerMain.setState(Constants.NumberStr.NUM_STR_FOUR);
            } else if(StringUtils.equals(prisonerMain1.getState(),Constants.NumberStr.NUM_STR_TWO)) {
                prisonerMain.setState(Constants.NumberStr.NUM_STR_ONE);
            } else {
                return Result.failure(ReturnCode.UPDATE_FAILED);
            }
            verificationMapper.updatePrisonerHcByParam(prisonerHc1,paramMap);
            // 填充prisonerTs信息
            prisonerTs.setPriNum(prisonerHc1.getId());
            prisonerTs.setPhoneNumber(prisonerHc1.getStartCheckPhone());
            prisonerTs.setFixedlineNumber(prisonerHc1.getStartCheckTel());
            prisonerTs.setType(Constants.NumberStr.NUM_STR_TEN);
            prisonerTs.setAdduserId(userDTO.getDepartid());
            // 只做保存
        } else if(StringUtils.equals(state,Constants.NumberStr.NUM_STR_FU_ONE)) {
            PrisonerHc prisonerHc1 = JsonUtil.toBean(data,PrisonerHc.class);
            prisonerHc.setPriReason(prisonerHc1.getPriReason());
            prisonerHc.setConmectuserid(userDTO.getAccount());
            prisonerHc.setConmectuserName(prisonerHc1.getConmectuserName());
            prisonerHc.setUpdateTime(date);
            prisonerHc.setUpdateUser(userDTO.getAccount());
            prisonerHc.setCreateTime(date);
            prisonerHc.setCreateUser(userDTO.getAccount());
            String conmectuserPhone = prisonerHc1.getConmectuserPhone();
            if(!StringUtils.isEmpty(conmectuserTelphone)) {
                conmectuserPhone = conmectuserPhone + "|" + conmectuserTelphone;
            }
            prisonerHc.setConmectuserPhone(conmectuserPhone);
            verificationMapper.updatePrisonerHcByParam(prisonerHc,paramMap);
            //户籍不完整，无街道信息的，司法局补全信息 - 核对成功
        }
        boolean blog = prisonerMain.updateById();
        boolean flag1 = prisonerTs.insert();
        if(b > 0 || b1) {
            if(blog && flag1) {
                //将数据同步到户籍所在省份
                if(StringUtils.equals(state,Constants.NumberStr.NUM_STR_ONE)) {
                    String localCode = CodeUrlUtils.getLocalCode();
                    //传入的转到的户籍地址省份code
                    PrisonerMain prisonerMain1 = prisonerMain.selectById();
                    String huji = prisonerMain1.getNativepro();
                    boolean flag = StringUtils.equals(localCode,huji);
                    if(!flag) {
                        BusinessUtils.handleMiddleProvinceData(priNum,localCode,huji,middleJdbcTemplate);
                    }
                }
            }
        }
        return Result.success();
    }

    /**
     * 批量修改核查状态
     * @param prinums prinums
     * @param state state
     * @param data data
     * @param userDTO 当前登录用户
     * @return Result
     */
    @Override
    public Result updateHcStatePl(String prinums,String state,String data,UserDTO userDTO) throws ParseException {
        String[] split = prinums.split("\\|");
        for(String s : split) {
            Result result = updateHcState(s,state,data,userDTO);
            if(4000 == result.getCode()) {
                return Result.failure(ReturnCode.UPDATE_FAILED);
            }
        }
        return Result.success();
    }

    /**
     * 预安置管理 - 预安置人员发起核查 - 核查失败 - 再次发起核查
     * @param data data
     * @param userDTO 当前登录用户
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateAgreeState(String data,UserDTO userDTO) {
        PrisonerMain prisonerMain = JsonUtil.toBean(data,PrisonerMain.class);
        Date date1 = new Date();
        Map<String,String> paramMap = new HashMap<>(16);
        prisonerMain.setUpdateUser(userDTO.getAccount());
        prisonerMain.setUpdateTime(date1);
        //填充推送表
        PrisonerTs prisonerTs = new PrisonerTs();
        prisonerTs.setCreateUser(userDTO.getAccount());
        prisonerTs.setCreateTime(date1);
        prisonerTs.setUpdateUser(userDTO.getAccount());
        prisonerTs.setUpdateTime(date1);
        Map<String,Object> dataMap = JsonUtil.toMap(data);
        String startCheckPerson = dataMap.get("startCheckPerson").toString();
        String startCheckTimeStr = dataMap.get("startCheckTime").toString().replace("T"," ");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startCheckTime;
        try {
            startCheckTime = simpleDateFormat.parse(startCheckTimeStr);
        } catch(ParseException e) {
            throw new RuntimeException(e);
        }
        String startCheckTel = dataMap.get("startCheckTel").toString();
        String startCheckPhone = dataMap.get("startCheckPhone").toString();
        // 监狱重新发起核查
        prisonerMain.setState(Constants.NumberStr.NUM_STR_TWO);
        prisonerMain.setSex(DICTIONARY.getSexMap().get(prisonerMain.getSex()));
        PrisonerMain prisonerMain1 = prisonerMain.selectById();
        PrisonerHc prisonerHc = new PrisonerHc();
        prisonerHc.setPriNum(prisonerMain1.getPriNum());
        // 将原记录置为不可用状态
        prisonerHc.setSignFlag(Constants.NumberStr.NUM_STR_ONE);
        paramMap.put("priNum",prisonerMain.getPriNum());
        paramMap.put("signFlag",Constants.NumberStr.NUM_STR_ZERO);
        verificationMapper.updatePrisonerHcByParam(prisonerHc,paramMap);
        prisonerHc.setId(IdGen.strid());
        prisonerHc.setUpdateTime(date1);
        prisonerHc.setUpdateUser(userDTO.getAccount());
        prisonerHc.setCreateTime(date1);
        prisonerHc.setCreateUser(userDTO.getAccount());
        prisonerHc.setStartCheckTime(startCheckTime);
        prisonerHc.setStartCheckTel(startCheckTel);
        prisonerHc.setStartCheckPhone(startCheckPhone);
        prisonerHc.setStartCheckPerson(startCheckPerson);
        // 初始化状态信息
        prisonerHc.setPushState(Constants.NumberStr.NUM_STR_ZERO);
        prisonerHc.setFailurenum(Constants.NumberStr.NUM_STR_ONE);
        prisonerHc.setSpecialFlag(Constants.NumberStr.NUM_STR_ZERO);
        prisonerHc.setSignFlag(Constants.NumberStr.NUM_STR_ZERO);
        // 填充prisonerTs信息
        prisonerTs.setId(IdGen.strid());
        prisonerTs.setPriNum(prisonerHc.getId());
        prisonerTs.setPhoneNumber(startCheckPhone);
        prisonerTs.setFixedlineNumber(startCheckTel);
        prisonerTs.setAdduserId(userDTO.getDepartid());
        prisonerTs.setType(Constants.NumberStr.NUM_STR_TEN_ONE);
        //填充核查表的xjrctId
        prisonerHc.setXjrctId(prisonerTs.getId());
        //往回执中间表插入一条数据
        XjReceipt xjReceipt = new XjReceipt();
        xjReceipt.setXjid(prisonerHc.getXjrctId());
        xjReceipt.setPriNum(prisonerMain1.getPriNum());
        xjReceipt.setSendCode(prisonerMain1.getAdduserid());
        xjReceipt.setSendName(prisonerMain1.getAddusername());
        xjReceipt.setReceiveCode(prisonerMain1.getNativevill());
        xjReceipt.setReceiveName(prisonerMain1.getNativevillName());
        xjReceipt.setSessionFlag(Constants.NumberStr.NUM_STR_ZERO);
        xjReceipt.setFlag(Constants.NumberStr.NUM_STR_ONE);
        xjReceipt.setCreateUser(userDTO.getAccount());
        xjReceipt.setUpdateUser(userDTO.getAccount());
        xjReceipt.setCreateTime(date1);
        xjReceipt.setUpdateTime(date1);
        xjReceiptMapper.saveXjReceive(xjReceipt);
        //将数据同步到户籍所在省份
        if(prisonerHc.insert() && prisonerMain.updateById() && prisonerTs.insert()) {
            String localCode = CodeUrlUtils.getLocalCode();
            //传入的转到的户籍地址省份code
            String huji = prisonerMain1.getNativepro();
            String priNum = prisonerMain1.getPriNum();
            boolean flag = !StringUtils.equals(localCode,huji);
            if(flag) {
                BusinessUtils.handleMiddleProvinceData(priNum,localCode,huji,middleJdbcTemplate);
            }
        }
        return Result.success();
    }

    /**
     * 根据id查询核查表信息
     * @param id id
     * @return Map<String,Object>
     */
    @Override
    public Map<String,Object> getPrisonerHcById(String id) {
        Map<String,Object> prisonerHc = verificationMapper.getPrisonerHcById(id);
        String priNum = String.valueOf(prisonerHc.get("prinum"));
        String approval = String.valueOf(prisonerHc.get("approval"));
        if(StringUtils.contains(Constants.NumberStr.NUM_STR_FOUR,approval)) {
            PrisonerTs prisonerTs = prisonerTsMapper.selectOne(new QueryWrapper<PrisonerTs>().lambda()
                                                                                             .eq(PrisonerTs::getPriNum,priNum)
                                                                                             .eq(PrisonerTs::getType,Constants.NumberStr.NUM_STR_THREE)
                                                                                             .orderByDesc(PrisonerTs::getCreateTime)
                                                                                             .last("limit 1"));
            if(null != prisonerTs) {
                prisonerHc.put("sfsReason",prisonerTs.getPriReason());
            }
        }
        String critype = prisonerFxMapper.selectByPriNum(priNum);
        String critypeName = "";
        if(!StringUtils.isEmpty(critype)) {
            List<Map<String,String>> codeNameList = systemCodeMapper.getCodeNameByCodeId(Arrays.asList(critype.split(",")));
            List<String> nameList = new ArrayList<>(16);
            codeNameList.forEach(map -> nameList.add(String.valueOf(map.get("codeName"))));
            critypeName = StringUtils.join(nameList,',');
        }
        prisonerHc.put("critype",critypeName);
        if(null != prisonerHc.get("conmectuserPhone")) {
            String conmectuserPhone = prisonerHc.get("conmectuserPhone").toString();
            if(conmectuserPhone.contains("|")) {
                String phone = conmectuserPhone.substring(0,conmectuserPhone.indexOf('|'));
                prisonerHc.put("conmectuserPhone",phone);
                String telPhone = conmectuserPhone.substring(conmectuserPhone.indexOf('|') + 1);
                prisonerHc.put("conmectuserTelphone",telPhone);
            } else {
                prisonerHc.put("conmectuserPhone",conmectuserPhone);
            }
        }
        return prisonerHc;
    }

    /**
     * 根据罪犯编号查询核查信息
     * @param id id
     * @return List<Map < String,Object>>
     */
    @Override
    public List<Map<String,Object>> getPrisonerHcListByPriNum(String id) {
        return verificationMapper.getPrisonerHcListByPriNum(id);
    }

    /**
     * 预安置管理 - 预安置人员发起核查 - 核查失败 - 转入原侦查机关
     * @param data data
     * @param userDTO 当前登录用户
     * @return Result
     */
    @Override
    public Result saveZryzcjg(String data,UserDTO userDTO) throws ParseException {
        PrisonerMain prisonerMain = JsonUtil.toBean(data,PrisonerMain.class);
        Date date1 = new Date();
        Map<String,String> paramMap = new HashMap<>(16);
        prisonerMain.setUpdateUser(userDTO.getAccount());
        prisonerMain.setUpdateTime(date1);
        String priNum1 = prisonerMain.getPriNum();
        prisonerMain.setHjType(prisonerMainMapper.selectPrisonerMain(priNum1).getHjType());
        PrisonerTs prisonerTs = new PrisonerTs();
        prisonerTs.setCreateUser(userDTO.getAccount());
        prisonerTs.setCreateTime(date1);
        prisonerTs.setUpdateUser(userDTO.getAccount());
        prisonerTs.setUpdateTime(date1);
        Map<String,Object> dataMap = JsonUtil.toMap(data);
        String startCheckPerson = dataMap.get("startCheckPerson").toString();
        String startCheckTimeStr = dataMap.get("startCheckTime").toString().replace("T"," ");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startCheckTime = simpleDateFormat.parse(startCheckTimeStr);
        String startCheckTel = dataMap.get("startCheckTel").toString();
        String startCheckPhone = dataMap.get("startCheckPhone").toString();
        prisonerMain.setState(Constants.NumberStr.NUM_STR_TWO);
        PrisonerMain prisonerMain1 = prisonerMain.selectById();
        //填充核查表
        PrisonerHc prisonerHc = new PrisonerHc();
        prisonerHc.setUpdateUser(userDTO.getAccount());
        prisonerHc.setUpdateTime(date1);
        prisonerHc.setPriNum(prisonerMain1.getPriNum());
        prisonerHc.setSignFlag(Constants.NumberStr.NUM_STR_ONE);
        paramMap.put("priNum",prisonerMain.getPriNum());
        paramMap.put("signFlag",Constants.NumberStr.NUM_STR_ZERO);
        verificationMapper.updatePrisonerHcByParam(prisonerHc,paramMap);
        prisonerHc.setId(IdGen.strid());
        prisonerHc.setCreateUser(userDTO.getAccount());
        prisonerHc.setCreateTime(date1);
        prisonerHc.setUpdateUser(userDTO.getAccount());
        prisonerHc.setUpdateTime(date1);
        prisonerHc.setIntoUser(userDTO.getDepartid());
        prisonerHc.setStartCheckTime(startCheckTime);
        prisonerHc.setStartCheckTel(startCheckTel);
        prisonerHc.setStartCheckPhone(startCheckPhone);
        prisonerHc.setStartCheckPerson(startCheckPerson);
        prisonerHc.setSignFlag(Constants.NumberStr.NUM_STR_ZERO);
        if(Constants.NumberStr.NUM_STR_ZERO_TWO.equals(prisonerMain.getHjType())) {
            prisonerHc.setFailurenum(Constants.NumberStr.NUM_STR_ZERO);
            prisonerHc.setPushState(Constants.NumberStr.NUM_STR_ZERO);
        } else {
            prisonerHc.setFailurenum(Constants.NumberStr.NUM_STR_TWO);
            prisonerHc.setPushState(Constants.NumberStr.NUM_STR_ZERO);
            prisonerHc.setSpecialFlag(Constants.NumberStr.NUM_STR_ONE);
            prisonerHc.setSignFlag(Constants.NumberStr.NUM_STR_ZERO);
        }
        // 填充prisonerTs
        prisonerTs.setId(IdGen.strid());
        prisonerTs.setPriNum(prisonerHc.getId());
        prisonerTs.setPhoneNumber(startCheckPhone);
        prisonerTs.setFixedlineNumber(startCheckTel);
        prisonerTs.setAdduserId(userDTO.getDepartid());
        prisonerTs.setType(Constants.NumberStr.NUM_STR_TEN_TWO);
        //往回执中间表插入一条数据
        //核查表
        prisonerHc.setXjrctId(prisonerTs.getId());
        XjReceipt xjReceipt = new XjReceipt();
        xjReceipt.setXjid(prisonerHc.getXjrctId());
        xjReceipt.setPriNum(priNum1);
        xjReceipt.setSendCode(prisonerMain1.getAdduserid());
        xjReceipt.setSendName(prisonerMain1.getAddusername());
        xjReceipt.setReceiveCode(prisonerMain1.getNativevill());
        xjReceipt.setReceiveName(prisonerMain1.getNativevillName());
        xjReceipt.setSessionFlag(Constants.NumberStr.NUM_STR_ZERO);
        xjReceipt.setFlag(Constants.NumberStr.NUM_STR_ONE);
        xjReceipt.setCreateUser(userDTO.getAccount());
        xjReceipt.setUpdateUser(userDTO.getAccount());
        xjReceipt.setCreateTime(date1);
        xjReceipt.setUpdateTime(date1);
        xjReceiptMapper.saveXjReceive(xjReceipt);
        boolean byId = false;
        int b = 0;
        if(Constants.NumberStr.NUM_STR_ZERO_TWO.equals(prisonerMain1.getHjType())) {
            prisonerHc.setId(IdGen.strid());
            prisonerHc.setSignFlag(Constants.NumberStr.NUM_STR_ZERO);
            //查不清户籍人员在hc表中还没有数据，所以执行hc表的插入操作
            byId = prisonerHc.insert();
        } else {
            //户籍完整人员走到转入原侦察机关hc表已经有数据
            b = verificationMapper.insert(prisonerHc);
        }
        if(byId || b > 0) {
            if(prisonerTs.insert()) {
                String priNum = prisonerMain.getPriNum();
                prisonerMain.setSex(DICTIONARY.getSexMap().get(prisonerMain.getSex()));
                boolean updateById = prisonerMain.updateById();
                if(updateById) {
                    //根据传入的priNum 查询该罪犯是否转入当前省，如果转入当前省不用管，如果转入其他省份需要迁移一整套数据到原侦查机关的省份系统
                    //本系统的本地code
                    String localCode = CodeUrlUtils.getLocalCode();
                    //传入的转到的户籍地址省份code
                    String huji = prisonerMain.getNativepro();
                    boolean flag = !StringUtils.equals(localCode,huji);
                    if(flag) {
                        BusinessUtils.handleMiddleProvinceData(priNum,localCode,huji,middleJdbcTemplate);
                        return Result.success("保存成功");
                    }
                }
            }
        }
        return Result.success("保存成功");
    }

    /**
     * 预安置管理 - 预安置人员核查 - 待办工作 - 办理
     * @param data 业务数据
     * @param user 当前登录用户
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result savePrisonerMainAndHcVo(String data,UserDTO user) {
        Map<String,Object> paramMap = JsonUtil.toMap(data);
        Map<String,String> paramMap1 = new HashMap<>(16);
        // 只做保存标识
        String state = (String)paramMap.get("pushstate");
        // 1:推送,2:上报,3:退回监狱
        String type = (String)paramMap.get("pushState");
        String pushName = (String)paramMap.get("pushName");
        String priNum = (String)paramMap.get("priNum");
        Date date = new Date();
        //查询当前人的户籍信息
        PrisonerMain prisonerMain1 = prisonerMainMapper.selectOne(new QueryWrapper<PrisonerMain>().lambda()
                                                                                                  .eq(PrisonerMain::getPriNum,priNum)
                                                                                                  .last("limit 1"));
        PrisonerHc prisonerHc = verificationMapper.selectOne(new QueryWrapper<PrisonerHc>().lambda()
                                                                                           .eq(com.sinog.core.domain.PrisonerHc::getPriNum,priNum)
                                                                                           .eq(PrisonerHc::getSignFlag,Constants.NumberStr.NUM_STR_ZERO)
                                                                                           .last("limit 1"));
        prisonerHc.setUpdateUser(user.getAccount());
        prisonerHc.setUpdateTime(date);
        PrisonerTs prisonerTs = new PrisonerTs();
        prisonerTs.setOperationName(pushName);
        prisonerTs.setCreateUser(user.getAccount());
        prisonerTs.setCreateTime(date);
        prisonerTs.setUpdateUser(user.getAccount());
        prisonerTs.setUpdateTime(date);
        // 将随机id放到前面
        prisonerTs.setId(IdGen.strid());
        prisonerTs.setPushState(type);
        //推送或者只做保存
        if(Constants.NumberStr.NUM_STR_ONE.equals(type) || Constants.NumberStr.NUM_STR_FOUR.equals(state)) {
            PrisonerMain prisonerMain = JsonUtil.toBean(data,PrisonerMain.class);
            prisonerMain.setUpdateUser(user.getAccount());
            prisonerMain.setUpdateTime(date);
            //获取该服刑人员户籍地址
            String nativeproNameCodeId = (String)paramMap.get("nativepro");
            String nativecityNameCodeId = (String)paramMap.get("nativecity");
            String nativecouNameCodeId = (String)paramMap.get("nativecou");
            String nativevillNameCodeId = (String)paramMap.get("nativevill");
            String nativenum = (String)paramMap.get("nativenum");
            if (StringUtils.isNotBlank(nativeproNameCodeId)){
                Map<String,String> areaNames = areaCodeFullMapper.getAreaNames(nativeproNameCodeId,nativecityNameCodeId,nativecouNameCodeId,nativevillNameCodeId);
                if (areaNames == null){
                    return Result.failure(ReturnCode.SAVE_FAILED);
                }
                prisonerMain.setNativeproName(areaNames.get("shengName"));
                prisonerMain.setNativecityName(areaNames.get("dishiName"));
                prisonerMain.setNativecouName(areaNames.get("quxianName"));
                prisonerMain.setNativevillName(areaNames.get("jiedaoName"));
                if (StringUtils.isBlank(nativecityNameCodeId)){
                    prisonerMain.setNativecityName("");
                }
                if (StringUtils.isBlank(nativecouNameCodeId)){
                    prisonerMain.setNativecouName("");
                }
                if (StringUtils.isBlank(nativevillNameCodeId)){
                    prisonerMain.setNativevillName("");
                }
            } else {
                prisonerMain.setNativeproName("");
                prisonerMain.setNativecityName("");
                prisonerMain.setNativecouName("");
                prisonerMain.setNativevillName("");
            }
            prisonerMain.setNativenum(nativenum);
            // 赋值记录表
            prisonerTs.setNativepro(prisonerMain1.getNativepro());
            prisonerTs.setNativecity(prisonerMain1.getNativecity());
            prisonerTs.setNativecou(prisonerMain1.getNativecou());
            prisonerTs.setNativevill(prisonerMain1.getNativevill());
            prisonerTs.setNativeproName(prisonerMain1.getNativeproName());
            prisonerTs.setNativecityName(prisonerMain1.getNativecityName());
            prisonerTs.setNativecouName(prisonerMain1.getNativecouName());
            prisonerTs.setNativevillName(prisonerMain1.getNativevillName());
            prisonerTs.setNativenum(prisonerMain1.getNativenum());
            prisonerTs.setNewNativepro(prisonerMain.getNativepro());
            prisonerTs.setNewNativecity(prisonerMain.getNativecity());
            prisonerTs.setNewNativecou(prisonerMain.getNativecou());
            prisonerTs.setNewNativevill(prisonerMain.getNativevill());
            prisonerTs.setNewNativeproName(prisonerMain.getNativeproName());
            prisonerTs.setNewNativecityName(prisonerMain.getNativecityName());
            prisonerTs.setNewNativecouName(prisonerMain.getNativecouName());
            prisonerTs.setNewNativevillName(prisonerMain.getNativevillName());
            prisonerTs.setNewNativenum(nativenum);
            // 只做保存
            if(Constants.NumberStr.NUM_STR_FOUR.equals(state)) {
                //添加成功后在推送表中新增一条记录
                prisonerTs.setType(Constants.NumberStr.NUM_STR_TEN_FIVE);
                prisonerTs.setAdduserId(user.getDepartid());
                prisonerTs.setPriNum(prisonerHc.getId());
                prisonerTs.setPriReason(null == paramMap.get("priReason") ? null : (String)paramMap.get("priReason"));
                prisonerTs.setPhoneNumber(null == paramMap.get("phoneNumber") ? null : (String)paramMap.get("phoneNumber"));
                prisonerTs.setFixedlineNumber(null == paramMap.get("fixedLineNumber") ? null : (String)paramMap.get("fixedLineNumber"));
                prisonerTs.insert();
                return Result.success();
            }
            // 推送state
            String userLevel = user.getLevel();
            if(StringUtils.equals(userLevel,Constants.OrgLevel.LEVEL_SFT)) {
                String localCode = CodeUrlUtils.getLocalCode();
                if(StrUtil.containsEquals(localCode,Constants.XzqhCode.BEIJING,Constants.XzqhCode.TIANJIN,Constants.XzqhCode.SHANGHAI,Constants.XzqhCode.CHONGQING)) {
                    prisonerHc.setPushState(Constants.NumberStr.NUM_STR_ONE);
                } else {
                    prisonerHc.setPushState(Constants.NumberStr.NUM_STR_TWO);
                }
                prisonerTs.setType(Constants.NumberStr.NUM_STR_FIVE);
            } else if(StringUtils.equals(userLevel,Constants.OrgLevel.LEVEL_DSSFJ)) {
                prisonerHc.setPushState(Constants.NumberStr.NUM_STR_ONE);
                prisonerTs.setType(Constants.NumberStr.NUM_STR_FOUR);
            } else if(StringUtils.equals(userLevel,Constants.OrgLevel.LEVEL_QXSFJ)) {
                prisonerHc.setPushState(Constants.NumberStr.NUM_STR_ZERO);
                // 司法局推送后将state改为2
                prisonerMain.setState(Constants.NumberStr.NUM_STR_TWO);
                prisonerTs.setType(Constants.NumberStr.NUM_STR_THREE);
            }
            // 往回执中间表插入一条数据
            if(!StringUtils.equals(prisonerMain1.getNativevill(),nativevillNameCodeId)) {
                XjReceipt xjReceipt = new XjReceipt();
                xjReceipt.setXjid(prisonerTs.getId());
                // 发送方应该是监狱
                xjReceipt.setPriNum(prisonerMain1.getPriNum());
                xjReceipt.setSendCode(user.getDepartid());
                xjReceipt.setSendName(user.getDepartName());
                xjReceipt.setReceiveCode(prisonerTs.getNewNativevill());
                xjReceipt.setReceiveName(prisonerTs.getNewNativevillName());
                xjReceipt.setSessionFlag(Constants.NumberStr.NUM_STR_ZERO);
                xjReceipt.setFlag(Constants.NumberStr.NUM_STR_ONE);
                xjReceipt.setCreateUser(user.getAccount());
                xjReceipt.setUpdateUser(user.getAccount());
                xjReceipt.setCreateTime(date);
                xjReceipt.setUpdateTime(date);
                // 往核查表中的字段推送标识
                prisonerHc.setXjrctId(prisonerTs.getId());
                xjReceiptMapper.saveXjReceive(xjReceipt);
            }
            prisonerMain.insertOrUpdate();
            // 上报流程
        } else if(Constants.NumberStr.NUM_STR_TWO.equals(type)) {
            String userLevel = user.getLevel();
            if(StringUtils.equals(userLevel,Constants.OrgLevel.LEVEL_DSSFJ)) {
                prisonerHc.setPushState(Constants.NumberStr.NUM_STR_THREE);
                prisonerTs.setType(Constants.NumberStr.NUM_STR_SEVEN);
            } else if(StringUtils.equals(userLevel,Constants.OrgLevel.LEVEL_QXSFJ)) {
                String localCode = CodeUrlUtils.getLocalCode();
                if(StrUtil.containsEquals(localCode,Constants.XzqhCode.BEIJING,Constants.XzqhCode.TIANJIN,Constants.XzqhCode.SHANGHAI,Constants.XzqhCode.CHONGQING)) {
                    prisonerHc.setPushState(Constants.NumberStr.NUM_STR_THREE);
                } else {
                    prisonerHc.setPushState(Constants.NumberStr.NUM_STR_TWO);
                }
                prisonerTs.setType(Constants.NumberStr.NUM_STR_SIX);
            }
            // 司法厅退回监狱
        } else if(Constants.NumberStr.NUM_STR_THREE.equals(type)) {
            prisonerHc.setFailurenum(String.valueOf(Integer.parseInt(prisonerHc.getFailurenum()) + 1));
            // 司法厅退回监狱
            prisonerHc.setPushState(Constants.NumberStr.NUM_STR_FOUR);
            if(Constants.NumberStr.NUM_STR_TWO.equals(prisonerHc.getFailurenum())) {
                prisonerHc.setSpecialFlag(Constants.NumberStr.NUM_STR_ONE);
            }
            // 判断如果无街道信息由司法厅退回后将state改为4,由监狱再次发起
            if(Constants.NumberStr.NUM_STR_TWO.equals(prisonerMain1.getState())) {
                prisonerMain1.setUpdateUser(user.getAccount());
                prisonerMain1.setUpdateTime(date);
                prisonerMain1.setState(Constants.NumberStr.NUM_STR_FOUR);
                prisonerMain1.insertOrUpdate();
            }
            prisonerTs.setType(Constants.NumberStr.NUM_STR_EIGHT);
        }
        //添加成功后在推送表中新增一条记录
        prisonerTs.setAdduserId(user.getDepartid());
        prisonerTs.setPriNum(prisonerHc.getId());
        prisonerTs.setPriReason(null == paramMap.get("priReason") ? null : (String)paramMap.get("priReason"));
        prisonerTs.setPhoneNumber(null == paramMap.get("phoneNumber") ? null : (String)paramMap.get("phoneNumber"));
        prisonerTs.setFixedlineNumber(null == paramMap.get("fixedLineNumber") ? null : (String)paramMap.get("fixedLineNumber"));
        boolean flag = prisonerTs.insertOrUpdate();
        paramMap1.put("priNum",priNum);
        paramMap1.put("signFlag",Constants.NumberStr.NUM_STR_ZERO);
        int b = verificationMapper.updatePrisonerHcByParam(prisonerHc,paramMap1);
        if(flag && b > 0) {
            return Result.success();
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 预安置管理 - 预安置人员核查 - 核查中 - 签收
     * @param priNum 服刑人员编号
     * @param type type
     * @param userDTO 当前登录用户
     */
    @Override
    public Result signFor(String priNum,String type,UserDTO userDTO) {
        String processType = Constants.HnInterfaceDocking.ZERO_SEVEN_ZERO_TWO_A;
        // 执行节点对应签收节点
        switch(type) {
            case Constants.NumberStr.NUM_STR_ONE:
                processType = Constants.HnInterfaceDocking.ZERO_SEVEN_ZERO_TWO_A;
                break;
            case Constants.NumberStr.NUM_STR_TWO:
                processType = Constants.HnInterfaceDocking.ZERO_SEVEN_ZERO_TWO_C;
                break;
            case Constants.NumberStr.NUM_STR_THREE:
                processType = Constants.HnInterfaceDocking.ZERO_SEVEN_ZERO_TWO_D;
                break;
            default:
                break;
        }
        HnInterfaceOpposite hnInterfaceOpposite = hnInterfaceOppositeMapper.selectHnInterfaceOppositeByPriNum(priNum,processType);
        if(null != hnInterfaceOpposite) {
            switch(type) {
                case Constants.NumberStr.NUM_STR_ONE:
                    if(Constants.NumberStr.NUM_STR_ZERO.equals(hnInterfaceOpposite.getHcType())) {
                        hnInterfaceOpposite.setHcType(Constants.NumberStr.NUM_STR_ONE);
                        hnInterfaceOpposite.setPgType(Constants.NumberStr.NUM_STR_ZERO);
                        hnInterfaceOpposite.setXjType(Constants.NumberStr.NUM_STR_ZERO);
                    }
                    break;
                case Constants.NumberStr.NUM_STR_TWO:
                    if(Constants.NumberStr.NUM_STR_ZERO.equals(hnInterfaceOpposite.getPgType())) {
                        hnInterfaceOpposite.setHcType(Constants.NumberStr.NUM_STR_ONE);
                        hnInterfaceOpposite.setPgType(Constants.NumberStr.NUM_STR_ONE);
                        hnInterfaceOpposite.setXjType(Constants.NumberStr.NUM_STR_ZERO);
                    }
                    break;
                case Constants.NumberStr.NUM_STR_THREE:
                    if(Constants.NumberStr.NUM_STR_ZERO.equals(hnInterfaceOpposite.getXjType())) {
                        hnInterfaceOpposite.setHcType(Constants.NumberStr.NUM_STR_ONE);
                        hnInterfaceOpposite.setPgType(Constants.NumberStr.NUM_STR_ONE);
                        hnInterfaceOpposite.setXjType(Constants.NumberStr.NUM_STR_ONE);
                    }
                    break;
                default:
                    break;
            }
            if(hnInterfaceOpposite.insertOrUpdate()) {
                // 线程池执行
                String finalProcessType = processType;
                threadPoolConfig.taskExecutor().execute(() -> {
                    HnMessageVo hnMessage = JsonUtil.toBean(hnInterfaceOpposite.getMessageData(),HnMessageVo.class);
                    // 签收成功后返回签收案件状态值
                    HashMap<String,String> qsMap = new HashMap<>(16);
                    qsMap.put("KBMBAH",null == hnMessage.getKbmbah() ? "" : hnMessage.getKbmbah());
                    qsMap.put("RWH",null == hnMessage.getRwh() ? "" : hnMessage.getRwh());
                    qsMap.put("LCSLBH",null == hnMessage.getLcslbh() ? "" : hnMessage.getLcslbh());
                    qsMap.put("PROCESS_NO",finalProcessType);
                    qsMap.put("AJMC",null == hnMessage.getAjmc() ? "" : hnMessage.getAjmc());
                    qsMap.put("LCLX_CODE",Constants.HnInterfaceDocking.ZERO_SEVEN_ZERO_TWO);
                    qsMap.put("LCLX_NAME",Constants.HnInterfaceDocking.ZHIXINGJIESHOU);
                    qsMap.put("JSDWLX","4B");
                    Map<String,Map<String,String>> tsmessage = provinceCodes3Config.getTSMESSAGE();
                    Map<String,String> fsdwCodes = tsmessage.get("FSDW_CODE");
                    for(Map.Entry<String,String> fsdw : fsdwCodes.entrySet()) {
                        if(fsdw.getValue().indexOf(hnMessage.getFsdwCode())>=0){
                            qsMap.put("JSDW_CODE",fsdw.getKey());
                        }
                    }
                    qsMap.put("JSDW_NAME",null == hnMessage.getFsdwName() ? "" : hnMessage.getFsdwName());
                    qsMap.put("JSDWSZD",null == hnMessage.getFsdwszd() ? "" : hnMessage.getFsdwszd());
                    qsMap.put("JSDWXZQ_CODE",null == hnMessage.getJsdwxzqCode() ? "" : hnMessage.getJsdwxzqCode());
                    qsMap.put("JSDWXZQ_NAME",null == hnMessage.getJsdwxzqName() ? "" : hnMessage.getJsdwxzqName());
                    qsMap.put("FSDWLX","5D");
                    qsMap.put("FSDW_CODE",null == hnMessage.getJsdwCode() ? "" : hnMessage.getJsdwCode());
                    qsMap.put("FSDW_NAME",null == hnMessage.getJsdwName() ? "" : hnMessage.getJsdwName());
                    qsMap.put("FSDWSZD",null == hnMessage.getJsdwszd() ? "" : hnMessage.getJsdwszd());
                    qsMap.put("FSDWXZQ_CODE",null == hnMessage.getFsdwxzqCode() ? "" : hnMessage.getFsdwxzqCode());
                    qsMap.put("FSDWXZQ_NAME",null == hnMessage.getFsdwxzqName() ? "" : hnMessage.getFsdwxzqName());
                    qsMap.put("FS_TIME",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    qsMap.put("JGZT",Constants.HnInterfaceDocking.NUM_STR_SIX_ZERO_TWO);
                    qsMap.put("ZTMS",Constants.HnInterfaceDocking.QIANSHOU_SUCCESS);
                    qsMap.put("MESSAGE",Constants.HnInterfaceDocking.QIANSHOU_SUCCESS);
                    qsMap.put("YSR",null == userDTO ? "" : userDTO.getUsername());
                    qsMap.put("YSRDH",null == userDTO ? "" : userDTO.getTelphone());
                    qsMap.put("CBR",null == userDTO ? "" : userDTO.getUsername());
                    qsMap.put("CBRDH",null == userDTO ? "" : userDTO.getTelphone());
                    qsMap.put("ZIPNAME",null == hnMessage.getZipName() ? "" : hnMessage.getZipName());
                    xmlMinitoringService.makeFile(qsMap);
                });
                return Result.success();
            }
        }
        return Result.failure(ReturnCode.FAILURE);
    }

    /**
     * 根据户籍街道编码查询是否有对应的司法所存在
     * @param prisonerMain 基本信息
     * @return Result
     */
    @Override
    public Result selectUserByNativevill(PrisonerMain prisonerMain) {
        Map<String,String> configMap = new HashMap<>(16);
        //读取application-*.yml配置文件中属性
        ProvinceCodesConfig provinceCodesConfig = CodesHelper.getInstance();
        List<Map<String,String>> valueMapList = provinceCodesConfig.getValueMapList();
        for(Map<String,String> m : valueMapList) {
            configMap.putAll(m);
        }
        //获取省份编码
        String localCode = configMap.get(Constants.ConfigStr.LOCAL_CODE);
        //省份编码前两位
        String proId = localCode.substring(0,2);
        //户籍地址编码前两位
        String nativecou = prisonerMain.getNativecou();
        String nativevill = prisonerMain.getNativevill();
        String hjCode;
        if(StringUtils.isNotBlank(nativevill)) {
            hjCode = nativevill;
        } else {
            hjCode = nativecou;
        }
        if(hjCode.startsWith(proId)) {
            Department department = departmentMapper.getDepartIdByNativevill(hjCode);
            if(null == department) {
                return Result.failure(ReturnCode.USER_NOT_FONUD);
            }
            List<User> user = userLoginDetailsMapper.getUserByDepartId(department.getId());
            if(null == user) {
                return Result.failure(ReturnCode.USER_NOT_FONUD);
            }
        }
        return Result.success();
    }

    /**
     * 根据服刑人员编号查询服刑人员信息
     * @param priNum 罪犯编号
     * @return PrisonerMain
     */
    @Override
    public PrisonerMain getPrisonerMainByPriNum(String priNum) {
        return prisonerMainMapper.selectPrisonerMain(priNum);
    }

    /**
     * 将核查结果封装到map中并交给下面的流程执行
     * @param prisonerMain 主表信息
     * @param hc 核查表信息
     * @param flag true--核查成功  false--核查失败
     * @return Result
     */
    public Result hcResult(PrisonerMain prisonerMain,PrisonerHc hc,Boolean flag) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String,String> hcResult = new HashMap<>(16);
        //根据罪犯编号去查询湖南个性化对接存储记录表
        HnInterfaceOpposite hnInterfaceOpposite = hnInterfaceOppositeMapper.selectHnInterfaceOppositeByPriNum(hc.getPriNum(),Constants.HnInterfaceDocking.ZERO_SEVEN_ZERO_TWO_A);
        hnInterfaceOpposite.setHzHcZip(Constants.NumberStr.NUM_STR_ONE);
        if(hnInterfaceOpposite.insertOrUpdate()) {
            HnMessageVo hnMessage = JsonUtil.toBean(hnInterfaceOpposite.getMessageData(),HnMessageVo.class);
            hcResult.put("KBMRYBH",hnMessage.getKbmrybh());
            hcResult.put("KBMBAH",hnMessage.getKbmbah());
            hcResult.put("priNum",hc.getPriNum());
            hcResult.put("NAME",prisonerMain.getPName());
            hcResult.put("SC_DATE",sdf.format(new Date()));
            //true:同意 false:拒绝
            hcResult.put("SCJG_CODE",flag ? Constants.NumberStr.NUM_STR_ONE : Constants.NumberStr.NUM_STR_TWO);
            hcResult.put("SCJG_NAME",flag ? Constants.HnInterfaceDocking.AGREE : Constants.HnInterfaceDocking.NO_AGREE);
            hcResult.put("BYJSLY",hc.getPriReason());
            hcResult.put("PROCESS_NO",Constants.HnInterfaceDocking.ZERO_SEVEN_ZERO_TWO_B);
            hcResult.put("LCSLBH",hnMessage.getLcslbh());
            hcResult.put("AJMC",hnMessage.getAjmc());
            hcResult.put("LCLX_CODE",Constants.HnInterfaceDocking.ZERO_SEVEN_ZERO_TWO_B);
            hcResult.put("LCLX_NAME",Constants.HnInterfaceDocking.WANCHENG_HECHA);
            hcResult.put("JSDWLX","4B");
            Map<String,Map<String,String>> tsmessage = provinceCodes3Config.getTSMESSAGE();
            Map<String,String> fsdwCodes = tsmessage.get("FSDW_CODE");
            for(Map.Entry<String,String> fsdw : fsdwCodes.entrySet()) {
                if(fsdw.getValue().indexOf(hnMessage.getFsdwCode()) >= 0) {
                    hcResult.put("JSDW_CODE",fsdw.getKey());
                }
            }
            hcResult.put("JSDW_NAME",hnMessage.getFsdwName());
            hcResult.put("JSDWSZD",hnMessage.getFsdwszd());
            hcResult.put("JSDWXZQ_CODE",hnMessage.getJsdwxzqCode());
            hcResult.put("JSDWXZQ_NAME",hnMessage.getJsdwxzqName());
            hcResult.put("FSDWLX","5D");
            hcResult.put("FSDW_CODE",hnMessage.getJsdwCode());
            hcResult.put("FSDW_NAME",hnMessage.getJsdwName());
            hcResult.put("FSDWSZD",hnMessage.getJsdwszd());
            hcResult.put("FSDWXZQ_CODE",hnMessage.getFsdwxzqCode());
            hcResult.put("FSDWXZQ_NAME",hnMessage.getFsdwxzqName());
            hcResult.put("FS_TIME",sdf.format(new Date()));
            hcResult.put("YSR",hc.getConmectuserName());
            hcResult.put("YSRDH",hc.getConmectuserPhone().substring(hc.getConmectuserPhone().lastIndexOf("|") + 1));
            hcResult.put("CBR",hc.getConmectuserName());
            hcResult.put("CBRDH",hc.getConmectuserPhone().substring(hc.getConmectuserPhone().lastIndexOf("|") + 1));
            hcResult.put("ZIPNAME",hnMessage.getZipName());
            return xmlMinitoringService.processOut(hcResult);
        }
        return null;
    }

    /**
     * 根据服刑人员编号查找推送信息
     * @param priNum 服刑人员编号
     * @return Result
     */
    @Override
    public Result getPrisonerHcByPriNum(String priNum) {
        PrisonerHc prisonerHc = verificationMapper.selectHcByPriNum(priNum);
        if(null != prisonerHc) {
            String id = prisonerHc.getId();
            PrisonerTsVo prisonerTs = prisonerTsMapper.searchBaseInfoByPriNum(id,null,Constants.NumberStr.NUM_STR_EIGHT,null);
            if(null != prisonerTs) {
                return Result.success(prisonerTs);
            }
        }
        return Result.failure(ReturnCode.FAILURE);
    }

    /**
     * sfbadmin--系统管理--死数据列表
     * @param pageIndex 起始页 默认:0
     * @param pageSize 止页数 默认:50
     * @param sortField 排序字段
     * @param sortOrder 排序方式
     * @param sexKey 性别 1:男、2:女
     * @param nameKey 姓名
     * @param inputSource 录入来源 01:司法所补录的解矫人员,05:司法所补录的监狱人员,3.看守所录入的服刑人员,4:接口进入的看守所人员,5:监狱录入的服刑人员,6:接口进入的监狱服刑人员,7:社矫录入的服刑人员,8:接口进入的社矫人员,9:监狱通过excel导入,10:社矫通过excel导入,11:看守所通过excel导入,30:湖南看守所个性化对接
     * @param zdbjKey 重点帮教对象 1:是、2:否
     * @param shenKey 身份证
     * @param zmKey 罪名
     * @param fxKey 服刑单位
     * @param nativepro 省
     * @param nativecity 市
     * @param nativecou 区
     * @param nativevill 街道
     * @param rjStartDate 原判刑期起日
     * @param rjEndDate 释放日期
     * @return String
     */
    @Override
    public String getSsjList(Integer pageIndex,Integer pageSize,String sortField,String sortOrder,String sexKey,String nameKey,String inputSource,String zdbjKey,String shenKey,String zmKey,String fxKey,String nativepro,String nativecity,String nativecou,String nativevill,String rjStartDate,String rjEndDate) {
        //参数校验
        if(StringUtils.equals(sortField,Constants.NumberStr.NUM_STR_FU_ONE)) {
            sortField = null;
        }
        if(StringUtils.equals(sortOrder,Constants.NumberStr.NUM_STR_FU_ONE)) {
            sortOrder = null;
        }
        if(StringUtils.equals(nameKey,Constants.NumberStr.NUM_STR_FU_ONE)) {
            nameKey = null;
        }
        if(StringUtils.equals(sexKey,Constants.NumberStr.NUM_STR_FU_ONE)) {
            sexKey = null;
        }
        if(StringUtils.equals(inputSource,Constants.NumberStr.NUM_STR_FU_ONE)) {
            inputSource = null;
        }
        if(StringUtils.equals(zdbjKey,Constants.NumberStr.NUM_STR_FU_ONE)) {
            zdbjKey = null;
        }
        if(StringUtils.equals(shenKey,Constants.NumberStr.NUM_STR_FU_ONE)) {
            shenKey = null;
        }
        if(StringUtils.equals(zmKey,Constants.NumberStr.NUM_STR_FU_ONE)) {
            zmKey = null;
        }
        if(StringUtils.equals(fxKey,Constants.NumberStr.NUM_STR_FU_ONE)) {
            fxKey = null;
        }
        if(StringUtils.equals(nativepro,Constants.NumberStr.NUM_STR_FU_ONE)) {
            nativepro = null;
        }
        if(StringUtils.equals(nativecity,Constants.NumberStr.NUM_STR_FU_ONE)) {
            nativecity = null;
        }
        if(StringUtils.equals(nativecou,Constants.NumberStr.NUM_STR_FU_ONE)) {
            nativecou = null;
        }
        if(StringUtils.equals(nativevill,Constants.NumberStr.NUM_STR_FU_ONE)) {
            nativevill = null;
        }
        if(StringUtils.equals(rjStartDate,Constants.NumberStr.NUM_STR_FU_ONE)) {
            rjStartDate = null;
        }
        if(StringUtils.equals(rjEndDate,Constants.NumberStr.NUM_STR_FU_ONE)) {
            rjEndDate = null;
        }
        //身份证加密
        if(StringUtils.isNotBlank(shenKey)) {
            shenKey = Sm4.encryptEcb(shenKey);
        }
        Page<Map<String,String>> page = new Page<>(pageIndex + 1,pageSize);
        page.setSearchCount(false);
        long count = prisonerMainMapper.getSsjListCount(page,sortField,sortOrder,sexKey,nameKey,inputSource,zdbjKey,shenKey,zmKey,fxKey,nativepro,nativecity,nativecou,nativevill,rjStartDate,rjEndDate);
        List<Map<String,String>> verificationList = prisonerMainMapper.getSsjList(page,sortField,sortOrder,sexKey,nameKey,inputSource,zdbjKey,shenKey,zmKey,fxKey,nativepro,nativecity,nativecou,nativevill,rjStartDate,rjEndDate);
        //把监狱与和对应的省份匹配
        Map<Object,Object> mapProvince = stringRedisTemplate.opsForHash().entries("province");
        for(Map<String,String> item : verificationList) {
            if(StringUtils.isEmpty(item.get("pdanweiName"))) {
                item.put("pdanweiName","");
            } else if(mapProvince.get(item.get("prinum").substring(0,2) + "0000")!=null) {
                item.put("pdanweiName",mapProvince.get(item.get("prinum").substring(0,2) + "0000") + "-" + item.get("pdanweiName"));
            }
        }
        return JsonUtil.toText(count,verificationList);
    }

    @Override
    public PrisonerHc getPrisonerHcByState(String priNum,String state) {
        return verificationMapper.getPrisonerHcByState(priNum,state);
    }
}